package com.butterfly.hotkey.worker.holder;

import com.butterfly.hotkey.core.cache.CaffeineCacheManager;
import com.butterfly.hotkey.core.cache.ICacheManager;
import com.butterfly.hotkey.core.constant.NumConst;
import com.butterfly.hotkey.core.model.AppCacheModel;
import com.butterfly.hotkey.worker.constants.WorkerConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.butterfly.hotkey.core.constant.NumConst.SIXTEEN;

/**
 * 处理从client端发过来的key，每个APP都会有一份缓存
 *
 * @author butterfly
 * @version 1.0
 */
public class KeyCacheHolder {

    private static final String DEFAULT = "default";

    /**
     * 每个APP的
     * key - appName
     * value - ICacheManager
     */
    private final static Map<String, ICacheManager> CACHE_MAP = new ConcurrentHashMap<>(SIXTEEN);

    /**
     * 获取APP关联的窗口缓存
     *
     * @param appName appName
     * @return ICacheManager
     */
    public static ICacheManager getWindowCacheManager(String appName) {
        // APP的窗口仅保存1分钟，1分钟不热，基本也不会热
        ICacheManager iCacheManager = CACHE_MAP.get(appName);
        if (iCacheManager != null) {
            return iCacheManager;
        }
        CaffeineCacheManager defaultCache = new CaffeineCacheManager(defaultKeyCache(), NumConst.SIXTY);
        CACHE_MAP.put(appName, defaultCache);
        return defaultCache;
    }

    /**
     * 默认的配置信息缓存配置
     *
     * @return AppCacheModel
     */
    public static AppCacheModel defaultKeyCache() {
        return AppCacheModel.Builder.builder()
                .initialCapacity(WorkerConst.DEFAULT_ALL_KEY_INIT_SIZE)
                .maximumSize(WorkerConst.DEFAULT_ALL_KEY_MAX_SIZE)
                .build();
    }

}
